<template>
	<view class="rental-detail">
		<!-- 加载中状态 -->
		<u-loading-page :loading="loading" loadingText="加载中..."></u-loading-page>

		<!-- 用户信息 -->
		<view class="user-card">
			<view class="user-avatar">
				<u-avatar :src="'/static/images/avatar.png'" shape="square" size="100rpx"></u-avatar>
			</view>
			<view class="user-info">
				<view class="user-name">{{ rentalInfo.username || '--' }}</view>
				<view class="order-time">手机号：{{ rentalInfo.mobile || '--' }}</view>
			</view>
		</view>

		<!-- 租赁人信息 -->
		<view class="info-section">
			<view class="section-title">租赁人信息</view>
			<view class="info-item">
				<text class="info-label">姓名</text>
				<text class="info-value">{{ rentalInfo.username || '--' }}</text>
			</view>
			<view class="info-item">
				<text class="info-label">手机号</text>
				<text class="info-value">{{ rentalInfo.mobile || '--' }}</text>
			</view>
			<view class="info-item">
				<text class="info-label">身份证号</text>
				<text class="info-value">{{ rentalInfo.usernum || '--' }}</text>
			</view>
		</view>

		<!-- 租赁信息 -->
		<view class="info-section">
			<view class="section-title">租赁信息</view>
			<view class="info-item">
				<text class="info-label">租期起租日</text>
				<text class="info-value">{{ formatDate(rentalInfo.lease_start_time) || '--' }}</text>
			</view>
			<view class="info-item">
				<text class="info-label">租期到期日</text>
				<text class="info-value">{{ formatDate(rentalInfo.lease_end_time) || '--' }}</text>
			</view>
			<view class="info-item">
				<text class="info-label">租赁时长</text>
				<text class="info-value">{{ rentalInfo.lease_time || '--' }}个月</text>
			</view>
			<view class="info-item">
				<text class="info-label">出租方式</text>
				<text class="info-value">{{ rentalInfo.lease_type || '--' }}</text>
			</view>
			<view class="info-item" v-if="hasSignedImages">
				<text class="info-label">签署照片</text>
				<view class="preview-container" @click="previewSignedImages">
					<image :src="firstSignedImage" mode="aspectFill" class="signature-image"></image>
					<u-icon name="arrow-right" color="#999" size="16"></u-icon>
				</view>
			</view>
		</view>

		<!-- 标签页 -->
		<u-tabs
			v-if="!loading"
			:list="tabList"
			:current="currentTabIndex"
			@change="tabChange"
			:activeStyle="{
				color: '#333',
				fontWeight: '500',
				fontSize: '30rpx'
			}"
			:inactiveStyle="{
				color: '#999',
				fontSize: '26rpx'
			}"
			:itemStyle="{
				height: '80rpx',
				padding: '0 49rpx 0 0',
				margin: '0 30rpx'
			}"
			:lineHeight="0"
		></u-tabs>

		<!-- 账单信息卡片 -->
		<view v-if="activeTab === 'bill'">
			<view v-for="(bill, index) in billList" :key="index" class="bill-card" :class="{ overdue: bill.status === 'overdue' }">
				<view class="bill-status" :class="'status-' + bill.status">
					{{ bill.statusText }}
				</view>
				<view v-for="(item, i) in bill.items" :key="i" class="bill-row">
					<text class="label">{{ item.label }}</text>
					<text class="value" :class="{ amount: item.isAmount }">
						{{ item.value }}
					</text>
				</view>
			</view>
		</view>

		<!-- 商品信息卡片 -->
		<view v-else-if="activeTab === 'product'" class="info-card">
			<view class="info-item">
				<text class="info-label">商品名称：</text>
				<text class="info-value">{{ rentalInfo.product_name || '--' }}</text>
			</view>
			<view class="info-item">
				<text class="info-label">规格：</text>
				<text class="info-value">{{ rentalInfo.product_attr || '--' }}</text>
			</view>
			<view class="info-item">
				<text class="info-label">采购价格：</text>
				<text class="info-value">¥{{ rentalInfo.purchase_price || '0.00' }}</text>
			</view>
		</view>

		<!-- 合同信息卡片 -->
		<view v-else-if="activeTab === 'contract'" class="contract-card">
			<view v-if="!rentalInfo.contract || rentalInfo.contract.length === 0" class="no-data">
				<view class="empty-container">
					<u-icon name="file-text" size="80" color="#c0c4cc"></u-icon>
					<text class="empty-text">暂无合同信息</text>
				</view>
			</view>
			<view v-else class="contract-list">
				<view v-for="(item, index) in rentalInfo.contract" :key="index" class="contract-item">
					<view class="contract-item-main">
						<view class="contract-info">
							<view class="contract-title">{{ item.name || '合同' + (index + 1) }}</view>
							<view class="contract-content">
								<view v-if="item.guarantor || item.guarantor_name">保障人: {{ item.guarantor || item.guarantor_name }}</view>
								<view v-else>保障人: 无</view>
								<view v-if="item.guarantee_start_time && item.guarantee_end_time">
									保障期限: {{ formatDate(item.guarantee_start_time, 'YYYY.MM.DD') }}-{{ formatDate(item.guarantee_end_time, 'YYYY.MM.DD') }}
								</view>
								<view v-else-if="item.guarantee_period">保障期限: {{ item.guarantee_period }}</view>
								<view v-else>保障期限: 无</view>
							</view>
						</view>
						<view class="contract-status">
							<view class="status-line">合同</view>
							<view class="status-line">生效中</view>
						</view>
					</view>
					<view class="contract-item-btn" @click="lookAgreement(item.weituo_url || item.ruzhu_url)">去查看>></view>
				</view>
			</view>
		</view>
	</view>
</template>

<script>
import { getRentalDetail } from '@/api/modules/rental';
import { formatDate as formatDateUtil } from '@/utils/common';

export default {
	data() {
		return {
			id: '',
			loading: false,
			currentTabIndex: 0,
			tabList: [
				{ name: '账单信息', value: 'bill' },
				{ name: '商品信息', value: 'product' },
				{ name: '合同信息', value: 'contract' }
			],
			activeTab: 'bill', // 默认显示账单信息
			billList: [],
			rentalInfo: {
				// 用户信息
				mobile: '',
				username: '',
				usernum: '',
				// 订单信息
				lease_time: 0,
				lease_start_time: 0,
				lease_end_time: 0,
				lease_type: '',
				// 商品信息
				product_name: '',
				product_attr: '',
				purchase_price: '0.00',
				// 合同信息
				contract: [],
				// 账单信息
				order_bill: []
			}
		};
	},
	onLoad(options) {
		if (options.id) {
			this.id = options.id;
			this.getRentalDetail();
		}
	},
	computed: {
		hasSignedImages() {
			return this.rentalInfo?.signed_images?.delivery_pics?.length > 0 || this.rentalInfo?.signed_images?.receipt_pics?.length > 0;
		},
		firstSignedImage() {
			if (!this.rentalInfo?.signed_images) return '';
			const defaultImage = '/static/images/default-image.png'; // Make sure this image exists in your project

			const firstDeliveryPic = this.rentalInfo.signed_images.delivery_pics?.[0];
			const firstReceiptPic = this.rentalInfo.signed_images.receipt_pics?.[0];

			return firstDeliveryPic || firstReceiptPic || defaultImage;
		},
		statusDescription() {
			const statusMap = {
				匹配中: '等待系统匹配租户中',
				租用中: '设备已出租，使用中',
				已完成: '租赁已完成',
				已取消: '租赁已取消'
			};
			return statusMap[this.rentalInfo.status] || '';
		}
	},
	methods: {
		// 查看协议（支持本地文件或网络文件）
		lookAgreement(contractUrl) {
			uni.navigateTo({
				url: `/package-purse/contractPreview/contractPreview?url=${encodeURIComponent(contractUrl)}`
			});
		},
		// 标签页切换
		tabChange(e) {
			this.currentTabIndex = e.index;
			this.activeTab = e.value;
		},

		// 预览图片
		previewImage(url) {
			if (!url) return;
			uni.previewImage({
				urls: [url],
				current: 0,
				indicator: 'number',
				loop: true
			});
		},

		// 预览签署图片
		previewSignedImages() {
			const images = [];

			// 添加交付图片
			if (this.rentalInfo.signed_images?.delivery_pics?.length) {
				images.push(...this.rentalInfo.signed_images.delivery_pics);
			}

			// 添加签收图片
			if (this.rentalInfo.signed_images?.receipt_pics?.length) {
				images.push(...this.rentalInfo.signed_images.receipt_pics);
			}

			if (images.length > 0) {
				uni.previewImage({
					urls: images,
					current: 0,
					indicator: 'number',
					loop: true
				});
			} else {
				uni.showToast({
					title: '暂无签署图片',
					icon: 'none'
				});
			}
		},

		goBack() {
			uni.navigateBack();
		},
		switchTab(tab) {
			this.activeTab = tab;
		},
		async getRentalDetail() {
			if (!this.id) return;

			this.loading = true;
			try {
				const res = await getRentalDetail(this.id);
				if (res.code === 1 && res.data) {
					const data = res.data;
					// 更新租赁信息
					this.rentalInfo = {
						...data.lease_user,
						...data.order,
						...data.product,
						contract: data.contract || [],
						order_bill: data.order_bill || []
					};
					// 处理账单列表
					this.processBillList(data.order_bill || []);
				} else {
					uni.showToast({
						title: res.msg || '获取详情失败',
						icon: 'none'
					});
				}
			} catch (error) {
				console.error('获取租赁详情失败:', error);
				uni.showToast({
					title: '获取详情失败，请重试',
					icon: 'none'
				});
			} finally {
				this.loading = false;
			}
		},

		// 处理账单列表
		processBillList(bills) {
			this.billList = bills.map((bill) => {
				const status = this.getBillStatus(bill);
				return {
					status: status,
					statusText: this.getStatusText(status),
					items: [
						{ label: '日期：', value: bill.date },
						{ label: '期数：', value: `第${bill.period}期` },
						{ label: '金额：', value: `¥${bill.amount}`, isAmount: true }
					]
				};
			});
		},

		// 获取账单状态
		getBillStatus(bill) {
			const now = Math.floor(Date.now() / 1000);
			const billDate = new Date(bill.date);
			billDate.setDate(billDate.getDate() + 1); // 给一天宽限期
			const dueDate = Math.floor(billDate.getTime() / 1000);

			if (now > dueDate) {
				return 'overdue';
			}
			return 'completed';
		},

		// 获取状态文本
		getStatusText(status) {
			const statusMap = {
				completed: '已完成',
				overdue: '已逾期',
				pending: '待支付'
			};
			return statusMap[status] || '未知';
		},

		// 格式化日期
		formatDate(timestamp, format = 'YYYY/MM/DD') {
			return formatDateUtil(timestamp, format);
		},
		handleReturn() {
			uni.showModal({
				title: '确认归还',
				content: '请确认租户已归还设备并检查设备状态',
				success: (res) => {
					if (res.confirm) {
						uni.showLoading({ title: '处理中...' });
						setTimeout(() => {
							uni.hideLoading();
							uni.showToast({
								title: '归还成功',
								icon: 'success'
							});
							setTimeout(() => {
								uni.navigateBack();
							}, 1500);
						}, 1000);
					}
				}
			});
		},
		handleCancel() {
			uni.showModal({
				title: '取消出租',
				content: '确定要取消本次出租吗？',
				success: (res) => {
					if (res.confirm) {
						uni.showLoading({ title: '处理中...' });
						setTimeout(() => {
							uni.hideLoading();
							uni.showToast({
								title: '已取消',
								icon: 'success'
							});
							setTimeout(() => {
								uni.navigateBack();
							}, 1500);
						}, 1000);
					}
				}
			});
		},
		handleReRent() {
			uni.showToast({
				title: '功能开发中',
				icon: 'none'
			});
		},
		callTenant() {
			// 拨打电话
			uni.makePhoneCall({
				phoneNumber: this.rentalInfo.tenantPhone,
				success: () => {
					console.log('拨打电话成功');
				},
				fail: () => {
					uni.showToast({
						title: '拨打电话失败',
						icon: 'none'
					});
				}
			});
		},
		contactCustomerService() {
			// 联系客服
			uni.navigateTo({
				url: '/pages/service/chat'
			});
		}
	}
};
</script>

<style lang="scss" scoped>
/* 通用卡片 */
.card {
	background: #fff;
	border-radius: 14rpx;
	margin: 20rpx 30rpx;
	padding: 30rpx;
}

/* 整体页面 */
.rental-detail {
	padding-bottom: 40rpx;

	/* 用户信息卡片 */
	.user-card {
		@extend .card;
		margin: 20rpx 0;
		display: flex;
		align-items: center;

		.user-avatar {
			margin-right: 20rpx;
		}

		.user-info {
			flex: 1;

			.user-name {
				font-weight: 500;
				font-size: 30rpx;
				color: #333;
				margin-bottom: 20rpx;
			}

			.order-time {
				font-size: 24rpx;
				color: #666;
			}
		}
	}

	/* 信息区块 */
	.info-section {
		@extend .card;
		margin-bottom: 20rpx;

		.section-title {
			font-size: 32rpx;
			font-weight: 500;
			color: #333;
			margin-bottom: 24rpx;
		}

		.info-item {
			display: flex;
			justify-content: space-between;
			padding: 24rpx 0;

			.info-label {
				font-weight: 400;
				font-size: 24rpx;
				color: #333333;
			}

			.info-value {
				font-weight: 400;
				font-size: 24rpx;
				color: #333333;
			}
		}

		.preview-container {
			display: flex;
			align-items: center;
			justify-content: flex-end;
			flex: 1;

			.signature-image {
				width: 120rpx;
				height: 80rpx;
				border-radius: 8rpx;
				margin-right: 16rpx;
			}
		}
	}

	/* 商品信息卡片 */
	.info-card {
		@extend .card;
		margin-top: 20rpx;
		padding: 38rpx 30rpx;
		.info-item {
			display: flex;
			font-weight: 400;
			font-size: 24rpx;
			color: #333333;
			margin-bottom: 33rpx;
			&:last-child {
				border-bottom: none;
				margin-bottom: 0;
			}
		}
	}

	/* 账单卡片 */
	.bill-card {
		@extend .card;
		position: relative;

		.bill-status {
			position: absolute;
			top: 30rpx;
			right: 30rpx;
			font-size: 24rpx;
			padding: 4rpx 16rpx;
			border-radius: 20rpx;
			font-weight: 500;

			&.status-completed {
				background: rgba(153, 153, 153, 0.1);
				color: #333;
			}

			&.status-overdue {
				background: rgba(255, 0, 0, 0.1);
				color: #ff0000;
			}
		}

		.bill-row {
			display: flex;
			margin-bottom: 20rpx;
			font-size: 28rpx;
			color: #333;
		}
	}

	/* 合同信息卡片 */
	.contract-card {
		padding: 0 30rpx;
		margin-top: 24rpx;

		.contract-list {
			display: flex;
			flex-direction: column;
			gap: 24rpx;
		}

		.contract-item {
			background: #fff;
			border-radius: 16rpx;
			padding: 32rpx 24rpx;
			box-shadow: 0 4rpx 20rpx rgba(0, 0, 0, 0.05);
		}
		.contract-item-main {
			display: flex;
			justify-content: space-between;
			align-items: center;
		}
		.contract-info {
			flex: 1;
		}

		.contract-title {
			font-size: 28rpx;
			font-weight: 500;
			color: #333333;
			line-height: 40rpx;
			margin-bottom: 8rpx;
		}

		.contract-content {
			font-size: 24rpx;
			font-weight: 400;
			color: #999999;
			line-height: 34rpx;
		}

		.contract-status {
			display: flex;
			flex-direction: column;
			align-items: center;
			margin-left: 20rpx;
			padding: 10rpx 0 10rpx 40rpx;
			border-left: rgba(161, 161, 161, 0.1) 2rpx solid;

			.status-line {
				font-size: 24rpx;
				font-weight: 400;
				color: #666666;
				line-height: 1.4;

				&.active {
					color: #3c9cff;
					font-weight: 500;
				}
			}
		}
		.contract-item-btn {
			width: 160rpx;
			height: 42rpx;
			background: #ff4400;
			border-radius: 6rpx;
			font-family: PingFang SC;
			font-weight: 500;
			font-size: 24rpx;
			color: #ffffff;
			text-align: center;
			line-height: 42rpx;
			margin-top: 24rpx;
		}
	}

	/* 操作按钮 */
	.action-buttons {
		position: fixed;
		left: 0;
		right: 0;
		bottom: 0;
		display: flex;
		padding: 20rpx 30rpx;
		background: #fff;
		box-shadow: 0 -2rpx 10rpx rgba(0, 0, 0, 0.05);

		.u-btn {
			flex: 1;
			margin: 0 10rpx;
			height: 88rpx;
			line-height: 88rpx;
			border-radius: 44rpx;
			font-size: 32rpx;

			&--primary {
				background: #ff4400 !important;
				border-color: #ff4400 !important;
			}

			&--default {
				background: #f5f5f5 !important;
				color: #333 !important;
				border: none !important;
			}
		}
	}
}

/* 空状态样式 */
.no-data {
	padding: 80rpx 30rpx;
	text-align: center;
	background: #fff;
	border-radius: 12rpx;
	box-shadow: 0 2rpx 12rpx rgba(0, 0, 0, 0.05);

	.empty-container {
		display: flex;
		flex-direction: column;
		align-items: center;
		justify-content: center;

		.u-icon {
			margin-bottom: 24rpx;
		}
	}

	.empty-text {
		font-size: 28rpx;
		color: #909399;
		line-height: 1.5;
	}
}
</style>
